package org.example.classtopia.Controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.example.classtopia.Common.Result.Result;
import org.example.classtopia.Model.Entity.User;
import org.example.classtopia.Model.vo.UserPageVO;
import org.example.classtopia.Model.vo.PageResultVO;
import org.example.classtopia.Repository.UserRepository;
import org.example.classtopia.Service.ManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;
import org.example.classtopia.Model.vo.PostPreviewVO;
import org.example.classtopia.Model.vo.ResourceDetailVO;
import org.example.classtopia.Model.vo.ManagerStatisticsVO;
import org.example.classtopia.Model.vo.UserLoginVO;

@Slf4j
@Tag(name = "管理员")
@RestController
@RequestMapping("/managers")
public class ManagerController {
    @Autowired
    private ManagerService managerService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private org.example.classtopia.Utils.TokenUtils tokenUtils;

    @Operation(summary = "修改用户状态")
    @PostMapping("/changeUserState")
    public Result<?> changeUserState(
        @RequestParam("userId") Long userId,
        @RequestParam("state") Integer state
    ) {
    // 这里假设managerService有对应的方法
    boolean success = managerService.changeUserState(userId, state);
        if (success) {
            return Result.success("操作成功");
        } else {
            return Result.error("操作失败");
        }
    }


    /**
     * 修改帖子状态
     * @param postId 要修改状态的帖子ID
     * @param state 目标状态（0-正常 1-隐藏 2-删除 3-封禁）
     * @return 操作结果，成功返回200
     */
    @Operation(summary = "修改帖子状态")
    @PostMapping("/changePostState")
    public Result<?> changePostState(
            @RequestParam("postId") Long postId,
            @RequestParam("state") Integer state
    ) {
        boolean success = managerService.changePostState(postId, state);
        if (success) {
            return Result.success("操作成功");
        } else {
            return Result.error("操作失败");
        }
    }
    
    @Operation(summary = "获取所有用户")
    @GetMapping("/getAllUsers")
    public Result<UserPageVO> GetAllUsers(
            @Parameter(description = "页码", example = "0")
            @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每一页数量", example = "10")
            @RequestParam(defaultValue = "10") int size,
            @Parameter(description = "用户状态，可选")
            @RequestParam(required = false) Integer state
    ){
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "id"));

        Page<User> UserPage;
        if (state != null) {
            UserPage = userRepository.findAllByStatus(state, pageable);
        } else {
            UserPage = userRepository.findAll(pageable);
        }
        UserPageVO userPageVO = new UserPageVO(
                UserPage.getContent(),
                UserPage.getTotalPages(),
                UserPage.getTotalElements(),
                UserPage.getNumber(),
                UserPage.getSize()
        );

        return Result.success(userPageVO);
    }

    /**
     * 修改资料状态
     * @param resourceId 被修改的资料ID
     * @param state 目标状态（0-删除，1-正常，2-封禁）
     * @return 操作结果，成功返回200
     */
    @Operation(summary = "修改资料状态")
    @PostMapping("/changeResourceState")
    public Result<?> changeResourceState(
            @RequestParam("resourceId") Long resourceId,
            @RequestParam("state") Integer state
    ) {
        boolean success = managerService.changeResourceState(resourceId, state);
        if (success) {
            return Result.success("操作成功");
        } else {
            return Result.error("操作失败");
        }
    }

    /**
     * 分页获取所有帖子（可按status/category筛选）
     * @param status 帖子状态，可选
     * @param categoryId 分类ID，可选
     * @param page 页码（默认0）
     * @param size 每页数量（默认10）
     * @return 分页帖子信息，成功返回200
     */
    @Operation(summary = "分页获取所有帖子（可按status/category筛选）")
    @GetMapping("/getAllPosts")
    public Result<PageResultVO<PostPreviewVO>> getAllPostsForManager(
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
        int offset = page * size;
        // 这里假设你有对应的Service方法，参数可选
        PageResultVO<PostPreviewVO> pageResult = managerService.getAllPostsFlexible(status, categoryId, offset, size);
        return Result.success(pageResult);
    }

    /**
     * 分页获取全部资源（可按分类、类型、状态筛选）
     */
    @Operation(summary = "分页获取全部资源（可按分类、类型、状态筛选）")
    @GetMapping("/getAllResources")
    public Result<PageResultVO<ResourceDetailVO>> getAllResources(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) String fileType,
            @RequestParam(required = false) Integer state
    ) {
        int offset = page * size;
        PageResultVO<ResourceDetailVO> pageResult = managerService.getAllResourcesFlexible(categoryId, fileType, state, offset, size);
        return Result.success(pageResult);
    }

    /**
     * 获取平台统计信息：用户数、帖子数、资源数、待处理举报数
     */
    @Operation(summary = "获取平台统计信息")
    @GetMapping("/getStatistics")
    public Result<ManagerStatisticsVO> getStatistics() {
        // 你需要在 managerService 实现这些统计方法
        long userCount = managerService.countAllUsers();
        long postCount = managerService.countAllPosts();
        long resourceCount = managerService.countAllResources();
        long pendingReportCount = managerService.countPendingReports();
        ManagerStatisticsVO vo = new ManagerStatisticsVO(userCount, postCount, resourceCount, pendingReportCount);
        return Result.success(vo);
    }

    @Operation(summary = "管理员登录")
    @PostMapping("/login")
    public Result<?> adminLogin(@RequestParam("username") String username,
                                @RequestParam("password") String password) {
        // 只允许纯数字账号
        if (!username.matches("\\d+")) {
            return Result.error("账号必须为纯数字");
        }
        // 查询用户
        User user = userRepository.findByNickname(username);
        if (user == null) {
            return Result.error("账号不存在");
        }
        // 检查密码
        if (!user.getPassword().equals(password)) {
            return Result.error("密码错误");
        }
        // 检查角色（假设管理员role为1）
        if (user.getRole() == null || user.getRole() != 1) {
            return Result.error("非管理员账号");
        }
        // 生成token
        String token = tokenUtils.getToken(user.getId().toString(), user.getRole().toString());
        // 构造返回VO并带token
        java.util.Map<String, Object> result = new java.util.HashMap<>();
        result.put("username", user.getNickname());
        result.put("userId", user.getId());
        result.put("status", user.getStatus());
        result.put("role", user.getRole());
        result.put("token", token);
        return Result.success(result);
    }
}